/**
 * Created by 小敏哥 on 2017/8/21.
 */
import {TEST_IMG,INSURANCE_IMG,IDCARD_OBVERSE_IMG,IDCARD_BACK_IMG,TAX_IMG,LICENSE_OBVERSE_IMG,LICENSE_BACK_IMG,USERANDCARD_IMG,CERTIFICATE_IMG} from './actionsTypes';
import {Toast} from 'antd-mobile';
import uploadService from '../services/uploadService';


export const testImage = data => ({type: TEST_IMG, data: data}); //测试图片
export const insuranceImage = data => ({type: INSURANCE_IMG, data: data}); //交强险
export const idCardObverseImage = data => ({type: IDCARD_OBVERSE_IMG, data: data}); //身份证正面
export const idCardBackImage = data => ({type: IDCARD_BACK_IMG, data: data}); //身份证背面
export const taxImage = data => ({type: TAX_IMG, data: data}); //车船税
export const licenseObverseImage = data => ({type: LICENSE_OBVERSE_IMG, data: data}); //行驶证正面
export const licenseBackImage = data => ({type: LICENSE_BACK_IMG, data: data}); //行驶证反面
export const userAndCardImage = data => ({type: USERANDCARD_IMG, data: data}); //用户手持身份证
export const certificateImage = data => ({type: CERTIFICATE_IMG, data: data}); //用户手持身份证

/**
 * imgData:base64格式图片数据
 *imgSources：图片对应redux数据源
 * */
export const uploadImage = (imgData, imgSources,errorCallBack) => {
    return (dispatch, getState) => {
        Toast.hide();
        Toast.loading("正在上传", 30, () => { Toast.fail('上传失败', 2);errorCallBack&&errorCallBack()});
        //上传前重新初始化数据
        imgSources&&dispatch(imgSources({
            url:'',
            loaded:false
        }));
        let uploadimgData = {
            content: imgData.substr((imgData.indexOf('base64,') + 7)), //只上传图片流
            format: 'jpg',
            channel: sessionStorage.getItem('userType') || 'app',
            watermark: true, //加水印
            bizType: 'inspection',
        };
        uploadService.uploadImg(uploadimgData).then((resultData) => {
            Toast.hide();
            if (resultData.code === 0) {
                imgSources&&dispatch(imgSources({
                    url:resultData.data.url,
                    loaded:true
                }));
                Toast.success('上传成功',1);
            } else {
                Toast.info(resultData.msg, 2);
                errorCallBack&&errorCallBack()
            }
        }).catch(() => {
            Toast.fail('上传失败', 2);
            errorCallBack&&errorCallBack()
        });
    }
};
